package com.ksl.kinglockguard.network;

import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Build.VERSION;
import android.text.TextUtils;

import com.ksl.kinglockguard.data.Constants;
import com.ksl.kinglockguard.data.SharePreferenceSdkData;
import com.ksl.kinglockguard.data.UserCountHabit;
import com.ksl.kinglockguard.gamelock.ScreenLockService;
import com.ksl.kinglockguard.utils.DeleteSdCacheUtil;
import com.ksl.kinglockguard.utils.ErrorRecordUtil;
import com.lsk.open.core.MyLog;
import com.lsk.open.core.net.NetConnectTask;
import com.lsk.open.core.net.NetConnectTask.TaskListener;
import com.lsk.open.core.net.NetHeadUtils;
import com.lsk.open.core.utils.ProductInfoUtils;

/**
 * @author kinsgame
 */
@SuppressLint("NewApi")
public class NetworkTask {

	private static final String TAG = "NetworkUtil";
	public static int count = 0;

	/**
	 * 首页列表和H5游戏列表接口
	 */
	public static final String URL="http://apiv2.spol.kingsgame.cn/";//线上正式接口
//    public static final String URL = "http://apiv2.screenlock.local.kingsgame.cn/";// 内网测试接口
    //	public static final String URL = "http://apiv2.sptest.kingsgame.cn/";// 线上测试接口
	//  private static final String URL="http://apiv2.screenlock.net/";//内网测试接口
	//  http://xiaosuo.ggllq.com/docs/api/v2-guide.php 测试地址
	
	/**
	 * 支付接口
	 */
   //private static final String URL_UPLOAD_ORDER="http://mepapi.local.kingsgame.cn/index/index/api/order";
    private static final String URL_UPLOAD_ORDER="http://apiv3.spol.kingsgame.cn/Index/Index/api/order";
	 
   /**
	 * 网络类型(全部小写)
	 */
	private static String mNetworkType;

	private static boolean isUploadingUserCount;
	/*
	 * 线上 api测试域名 blueclean.ksdev.kingsgame.cn 测试附件下载地址
	 * bluecleanfile.ksdev.kingsgame.cn 测试后台 bluecleanadmin.ksdev.kingsgame.cn
	 * 
	 * 线上正式生产环境 blueclean.ksol.kingsgame.cn 测试附件下载地址
	 * bluecleanfile.ksol.kingsgame.cn 测试后台 bluecleanadmin.ksol.kingsgame.cn
	 */



	private static JSONObject getSendSecrityPara() {
		JSONObject request = new JSONObject();
		try {
			request.put("app_key", "391ef58892588b6c");
			request.put("time", System.currentTimeMillis());
			// request.put("sign ", KingsSystemUtils.getSignature());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		return request;
	}

	// 请求更新服务器
	private static final String URL_UPDATE_VERSION = URL + "Upgrade.json";

	public static NetConnectTask requestUpdateMyApp(final Context context) {
		NetConnectTask netTask = new NetConnectTask(context);

		netTask.execute(URL_UPDATE_VERSION, getSendSecrityPara().toString());

		return netTask;
	}

	static final class UpdateDomain {
		private static final int DOWNLOAD_Type_NORMAL = 1;
		private static final int DOWNLOAD_Type_AUTO = 2;
		private int status;
		// url: {"STATUS":1,"DATA":{
		// "LASTUPDATE":"1405064167","URL":"http:\/\/bluecleanfile.ksdev.kingsgame.cn\/apks\/201407\/11\/34f1\/53bf93e4ca034.apk",
		// "VERSION_NAME":"V1.0.0.140711_alpha","TYPE":"1"}}
		private long lastUpdate; // 该更新版本是何时上传到服务器的, 目前没用
		private String downloadUrl; // 下载地址
		private String versionName; // 新版本的版本名称
		// downloadType=1 表示"普通下载", 即需要弹出通知栏,提示用户发现更新,用户点击通知栏后开始下载.
		// downloadType=2 表示"静默下载", 即后台自动下载,不提示用户.
		private int downloadType;

		public UpdateDomain(String jsonobj) throws JSONException {
			super();
			JSONObject response = new JSONObject(jsonobj);
			this.status = response.getInt("STATUS");
			JSONObject data = response.getJSONObject("DATA");
			this.lastUpdate = data.getLong("LASTUPDATE");
			this.downloadUrl = data.getString("URL");
			this.downloadType = data.getInt("TYPE");
		}

		@Override
		public String toString() {
			return "UpdateDomain [status=" + status + ", lastUpdate="
					+ lastUpdate + ", donwloadUrl=" + downloadUrl
					+ ", versionName=" + versionName + ", downloadType="
					+ downloadType + "]";
		}
	}

	private static int getJsonType(JSONObject result) {
		try {

			JSONObject jb = result.getJSONObject("DATA");
			MyLog.i("ydy", "*********getJsonUrl** " + jb.toString());
			return jb.getInt("TYPE");
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return -1;
	}

	// 用户启动用应用　
	private static final String URL_BASE_INFO = URL + "ActivationStat.json";

	public static NetConnectTask requestFirstMyApp(final Context context) {
		NetConnectTask netTask = new NetConnectTask(context);

		netTask.execute(URL_BASE_INFO, getSendSecrityPara().toString());
		netTask.setListener(new TaskListener() {

			@Override
			public void onNoNetworking() {
				// TODO Auto-generated method stub

			}

			@Override
			public void onNetworkingError() {
				// TODO Auto-generated method stub

			}

			@Override
			public void onPostExecute(byte[] bytes) {
				MyLog.d(TAG,
						"requestFirstMyApp--------------onPostExecute ----- bytes: "
								+ new String(bytes));
				SharePreferenceSdkData.setFirstRegister(context, true);
			}

		});
		return netTask;
	}

	private static final String URL_LANUCHER_INFO = URL + "BootStat.json";

	public static NetConnectTask requestLanuchMyApp(final Context context) {
		String contents = SharePreferenceSdkData.getLanucherTimers(context);
		MyLog.i("jyh", "--------requestLanuchMyApp -----contents: " + contents);
		if (contents.isEmpty() || contents.equals("-1")) {
			MyLog.i("jyh", "requestLanuchMyApp contents is empty!!!");
			return null;
		}
		String[] times = contents.split(",");
		if (times.length == 0)
			return null;

		String sd = "";
		JSONObject jsonb = new JSONObject();
		try {
			JSONArray ja = new JSONArray();
			for (int i = 0; i < times.length; i++) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				if(times[i].equals("") || TextUtils.isEmpty(times[i]))
					continue;
				String after = sdf.format(new Date(Long.parseLong(times[i])));
				if (!sd.equals("") && after.equals(sd)) {
					continue;
				}
				sd = after;
				if (sd.equals(""))
					continue;
				ja.put(sd);
				if (ja.length() == 0)
					return null;
				jsonb.put("security", getSendSecrityPara());
				jsonb.put("content", ja);

			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		MyLog.i("jyh", "NetworkUtils requestLanuchMyApp upload content===="
				+ jsonb.toString());

		NetConnectTask netTask = new NetConnectTask(context);
		netTask.execute(URL_LANUCHER_INFO, jsonb.toString());
		netTask.setListener(new TaskListener() {

			@Override
			public void onNoNetworking() {
				// TODO Auto-generated method stub

			}

			@Override
			public void onNetworkingError() {
				// TODO Auto-generated method stub

			}

			@Override
			public void onPostExecute(byte[] bytes) {
				SharePreferenceSdkData.setLanucherTimers(context, -1);
				SharePreferenceSdkData.setLastUploadLauncherTimes(context,
						System.currentTimeMillis());
				SharePreferenceSdkData.setLastUploadBootstat(context, System.currentTimeMillis());
			}

		});
		return netTask;
	}

	/*
	 * 行为统计各种数据
	 */
	private static final String URL_ACTIVE_INFO = URL + "ActStat.json";

	// 解锁环左划、右划、跳转至手机、相机、短信以及解锁界面每个资源的查看次数。
	public static NetConnectTask requestUpdateUserCount(final Context context) {
		String content = UserCountHabit.countAllData(context);
		MyLog.d("jyh", "requestActiveMyApp-----------content: " + content);
		if (content.isEmpty() || content.equals("{}")) {
			return null;
		}
		NetConnectTask netTask = new NetConnectTask(context);

		isUploadingUserCount = true;
		netTask.execute(URL_ACTIVE_INFO, content);
		netTask.setListener(new TaskListener() {

			@Override
			public void onNoNetworking() {
				isUploadingUserCount = false;

			}

			@Override
			public void onNetworkingError() {
				isUploadingUserCount = false;

			}

			@Override
			public void onPostExecute(byte[] bytes) {
				MyLog.d(TAG, "requestActiveMyApp-----------onPostExecute: "
						+ new String(bytes));
				SharePreferenceSdkData.setLastUploadUserHabit(context,
						System.currentTimeMillis());
				UserCountHabit.clearCountData(context);
				isUploadingUserCount = false;
			}

		});

		return netTask;
	}

	private static String loadingApps = null;

	// 上传错误日志
	private static final String URL_UPLOAD_ERRORCONTENT = URL + "ApiLog.json";

	public static NetConnectTask requestUploadError(final Context context,
			String content) {
		MyLog.d("wmm", "requestUploadError-----------start ");
		NetConnectTask netTask = new NetConnectTask(context);
		netTask.setListener(new TaskListener() {
			@Override
			public void onNoNetworking() {
				MyLog.d("wmm", "requestUploadError-----------onNoNetworking: ");
			}

			@Override
			public void onNetworkingError() {
				MyLog.d("wmm",
						"requestUploadError-----------onNetworkingError: ");
			}

			@Override
			public void onPostExecute(byte[] bytes) {
				MyLog.d("wmm", "requestUploadError-----------onPostExecute: "
						+ new String(bytes));
				ErrorRecordUtil.deleteErrorLogFile();
			}
		});
		netTask.execute(URL_UPLOAD_ERRORCONTENT, content);
		return netTask;
	}

	// 请求首页列表资讯
	public static NetConnectTask requestMainPageList(final Context context,
			String content) {
		NetConnectTask netTask = new NetConnectTask(context);
		netTask.execute(URL + "Article.json", content);
		return netTask;
	}
	
	// 请求H5游戏列表
	public static NetConnectTask requestH5List(final Context context,
			String content) {
		NetConnectTask netTask = new NetConnectTask(context);
		MyLog.i("h5request", "requestH5List~~~~~h5 content is ~~~~"+content);
		netTask.execute(URL + "/Article.json", content);
//		netTask.execute("http://apiv2.screenlock.local.kingsgame.cn/" + "Article.json", content, null,
//				NetworkUtil.getSendHeader(context));
		return netTask;
	}

	// 请求焦点图广告
	public static NetConnectTask requestBanner(final Context context,
			String content) {
		NetConnectTask netTask = new NetConnectTask(context);
		netTask.execute(URL + "Banner.json", content);
		return netTask;
	}

	/**
	 * app下载完成的统计接口
	 * 
	 * @param context
	 * @param appid
	 * @param isCache
	 * @return
	 */
	public static NetConnectTask reportDownloadFinish(final Context context,
			final String appid, final boolean isCache) {
		String params = "";
		if (isCache) {
			String cache = SharePreferenceSdkData
					.getCacheDownloadAppid(context);
			String[] result = parseCache(cache);
			params = "appid=" + result[0] + getParams(context) + "&time="
					+ result[1];
		} else {
			params = "appid=" + appid + "&" + getParams(context) + "&time="
					+ System.currentTimeMillis() / 1000;
		}
		NetConnectTask netTask = new NetConnectTask(context);
		netTask.execute(URL + "DownloadFinish.json?" + params, null);
		netTask.setListener(new TaskListener() {
			@Override
			public void onPostExecute(byte[] bytes) {
				if (bytes != null) {
					try {
						JSONObject object = new JSONObject(new String(bytes));
						if (!object.isNull("errno")) {
							int errno = object.getInt("errno");
							if (errno != 200) {
								if (!isCache)
									cacheAppId(context, appid);
							} else {
								if (isCache)
									SharePreferenceSdkData
											.clearCacheAppId(context);
							}
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}

			@Override
			public void onNoNetworking() {
				if (!isCache) {
					cacheAppId(context, appid);
				}
			}

			@Override
			public void onNetworkingError() {
				if (!isCache) {
					cacheAppId(context, appid);
				}
			}
		});
		return netTask;
	}

	/**
	 * 将sharedpreference中缓存的appids解析出来
	 * 
	 * @param cache
	 * @return
	 */
	public static String[] parseCache(String cache) {
		String[] split = cache.split("\\|");
		int length = split.length;
		String ids = "";
		String times = "";
		for (int i = 0; i < length; i++) {
			String s = split[i];
			ids = ids + "_" + s.split(":")[0];
			times = times + "_" + s.split(":")[1];
		}
		String[] result = new String[2];
		result[0] = ids.substring(1);
		result[1] = times.substring(1);
		return result;
	}

	public static String getParams(Context context) {
		String imei = ProductInfoUtils.imie;
		if (imei == null) {
			imei = ProductInfoUtils.getIMEI(context);
		}
		String mc = ProductInfoUtils.macAddress;
		if (TextUtils.isEmpty(mc)) {
			mc = ProductInfoUtils.getMacAddress(context);
		}
		String product = Build.MODEL;
		String net = NetHeadUtils.getNetworkType(context);
		String apis = "F:SP_V:" + ProductInfoUtils.getVcode(context);
		String channel = ProductInfoUtils.getChannelName(context);
		String producer = Build.DEVICE;
		String sdk = Build.VERSION.SDK;
		String vcode = ProductInfoUtils.getVcode(context);
		String device_md5 = "";
		String params = "&imei=" + imei + "&mc=" + mc + "&product=" + product
				+ "&net=" + net + "&apis=" + apis + "&channel=" + channel
				+ "&producer=" + producer + "&sdk=" + sdk + "&vcode=" + vcode
				+ "&device-md5=" + device_md5;
		return params;
	}

	/**
	 * 将相应的appid缓存到sharedpreference中
	 * 
	 * @param context
	 * @param appid
	 */
	private static void cacheAppId(Context context, String appid) {
		SharePreferenceSdkData.cacheDownloadAppid(context, appid);
	}

	private static String getAppIdFromParams(String params) {
		String[] split = params.split("&");
		String appId = "";
		int size = split.length;
		for (int i = 0; i < size; i++) {
			String str = split[i];
			if (str.contains("appid")) {
				appId = str.substring(str.indexOf("=") + 1, str.length());
				break;
			}
		}
		return appId;
	}

	// 请求单条广告
	public static NetConnectTask requestSingleAd(final Context context,
			String content) {
		NetConnectTask netTask = new NetConnectTask(context);
		netTask.execute(URL, content);
		netTask.setListener(new TaskListener() {

			@Override
			public void onNoNetworking() {

			}

			@Override
			public void onNetworkingError() {

			}

			@Override
			public void onPostExecute(byte[] bytes) {
				MyLog.d(TAG, "requestSingleAd-----------onPostExecute: "
						+ new String(bytes));
			}
		});

		return netTask;
	}

//	public static NetConnectTask requestScreenLockFlag(final Context context) {
//		NetConnectTask netTask = new NetConnectTask(context);
//		netTask.execute(TOTAL_URL, getSendSecrityPara().toString());
//		return netTask;
//	}

	// 与服务器同步锁屏咨询显示策略
	private static final String STRATEGY_URL_STRING = URL + "Setting.json";

	public static NetConnectTask syncScreenLockStrategy(final Context context) {
		NetConnectTask netTask = new NetConnectTask(context);
		netTask.setListener(new TaskListener() {
			@Override
			public void onPostExecute(byte[] bytes) {
				try {

					JSONObject jsobject = new JSONObject(new String(bytes));
					MyLog.i("wmm", "syncScreenLockStrategy onPostExecute:  "
							+ jsobject.toString());
					if (!jsobject.isNull("data")) {
						SharePreferenceSdkData.setLastSyncStrategyTime(context,
								System.currentTimeMillis());
						JSONObject data = jsobject.getJSONObject("data");
						if (!data.isNull("refresh_interval")) {
							long interval = data.getLong("refresh_interval");
							SharePreferenceSdkData.setIntervalTime(context,
									interval * 60 * 60 * 1000);
						}
						if (!data.isNull("refresh_mode")) {
							SharePreferenceSdkData.setTraversalSwitch(context,
									data.getInt("refresh_mode"));
						}
						if (!data.isNull("gameIconDisplayDays")) {
							MyLog.i("jyh1", "~~~data.getInt()~~~"+data.getInt("gameIconDisplayDays"));
							MyLog.i("jyh1", "~~~SP.getH5IconDays(context)~~~"+SharePreferenceSdkData.getH5IconDays(context));
							//如果服务器端修改了gameIconDisplayDays这个字段，则重新开始计算天数
							if(data.getInt("gameIconDisplayDays") != SharePreferenceSdkData.getH5IconDays(context)){
								SharePreferenceSdkData.setH5IconDays(context,data.getInt("gameIconDisplayDays"));
								MyLog.i("jyh1", "~~~重置了h5开关~~~");
								SharePreferenceSdkData.setH5GameStatus(context, false);
								SharePreferenceSdkData.setDaysGone(context, 0);
							}
						}
					}
					//H5游戏开关，控制用户首次安装n天后才显示入口
					if(!SharePreferenceSdkData.getH5GameStatus(context)){
						MyLog.i("jyh1", "~~~h5开关未开启~~~");
						checkIfH5Show(context);
						if(SharePreferenceSdkData.getH5IconDays(context) == 0)
							SharePreferenceSdkData.setH5GameStatus(context, true);
					}else
						MyLog.i("jyh1", "~~~h5开关已经开启~~~");
						
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onNoNetworking() {
			}

			@Override
			public void onNetworkingError() {
				MyLog.i("wmm", "syncScreenLockStrategy error");
			}
		});
		netTask.execute(STRATEGY_URL_STRING, getSendSecrityPara().toString());
		return netTask;
	}
	
	private static void checkIfH5Show(Context context){
    	long installTime = SharePreferenceSdkData.getInstallTime(context);
    	if((System.currentTimeMillis() - installTime >= 24*60*60*1000)){
    		SharePreferenceSdkData.setDaysGone(context, SharePreferenceSdkData.getDaysGone(context)+1);
    		MyLog.i("jyh1", "~~~checkIfH5Show getDaysGone~~~"+SharePreferenceSdkData.getDaysGone(context));
    		MyLog.i("jyh1", "~~~checkIfH5Show getH5IconDays~~~"+SharePreferenceSdkData.getH5IconDays(context));
    		SharePreferenceSdkData.setInstallTime(context, System.currentTimeMillis());
    		if(SharePreferenceSdkData.getDaysGone(context) >= SharePreferenceSdkData.getH5IconDays(context)){//设置用户首次安装n天后，h5游戏的入口出现
    			SharePreferenceSdkData.setH5GameStatus(context, true);
    			MyLog.i("jyh1", "~~~setH5GameStatus(context, true)~~~");
    		}
    	}
    }
	
	// 用户兴趣推荐
//		public static NetConnectTask requestUserInterest(final Context context,
//				String content) {
//			NetConnectTask netTask = new NetConnectTask(context);
//			netTask.execute(URL + "/Profile.json", content, null,
//					NetworkUtil.getSendHeader(context));
//			return netTask;
//		}
	
	// 用户兴趣推荐
//	private static final String USER_INTEREST = URL + "Profile.json";
//
//	public static NetConnectTask requestUserInterest(final Context context) {
//		NetConnectTask netTask = new NetConnectTask(context);
//		netTask.setListener(new TaskListener() {
//			@Override
//			public void onPostExecute(byte[] bytes) {
//				try {
//					JSONObject jsobject = new JSONObject(new String(bytes));
//					MyLog.i("jyh1", "syncScreenLockStrategy onPostExecute:  "
//							+ jsobject.toString());
//					if (!jsobject.isNull("data")) {
//						JSONObject data = jsobject.getJSONObject("data");
//						SharePreferenceSdkData.setUserGroup(context, data.getString("group"));
//						SharePreferenceSdkData.setUserPreference(context, data.getString("preference"));
//					}
//					if (!jsobject.isNull("time")) {
//						JSONObject data = jsobject.getJSONObject("time");
//						long timeDuration = data.getLong("last");
//						SharePreferenceSdkData.setTimeDuration(context, timeDuration);
//					}
//				} catch (JSONException e) {
//					e.printStackTrace();
//				}
//			}
//
//			@Override
//			public void onNoNetworking() {
//			}
//
//			@Override
//			public void onNetworkingError() {
//				MyLog.i("jyh1", "user interest");
//			}
//		});
//		netTask.execute(USER_INTEREST, null, null, NetworkUtil.getSendHeader(context));
//		return netTask;
//	}
	
	// 用户兴趣推荐
	private static final String USER_INTEREST = URL + "Profile.json";

	public static NetConnectTask requestUserProfile(final Context context) {
		NetConnectTask netTask = new NetConnectTask(context);
		netTask.setListener(new TaskListener() {
			@Override
			public void onPostExecute(byte[] bytes) {
				try {
					JSONObject jsobject = new JSONObject(new String(bytes));
					MyLog.i("jyh", "requestUserProfile onPostExecute:  "
							+ jsobject.toString());
					SharePreferenceSdkData.setUserProfileUpdateTime(context, System.currentTimeMillis());
					if (!jsobject.isNull("data")) {
						JSONObject data = jsobject.getJSONObject("data");
						if(!data.isNull("group"))
							SharePreferenceSdkData.setUserGroup(context, data.getString("group"));
						if(!data.isNull("preference"))
							SharePreferenceSdkData.setUserPreference(context, data.getString("preference"));
						if(!data.isNull("location")){
							JSONArray location = data.getJSONArray("location");
							if(!location.isNull(1)){
								String area = location.getString(1);//一般是：中国  广东  深圳 ...
								if(area.equals(Constants.SHANG_HAI)){
									SharePreferenceSdkData.setUserInShanghaiFlag(context, true);
									MyLog.i("jyh", "~~~get user location in shanghai");
									}else{
										SharePreferenceSdkData.setUserInShanghaiFlag(context, false);
										MyLog.i("jyh", "~~~get user location not in shanghai");
									}
							}
						}
						
					}
					if (!jsobject.isNull("time")) {
						JSONObject data = jsobject.getJSONObject("time");
						long timeDuration = data.getLong("last");
						SharePreferenceSdkData.setTimeDuration(context, timeDuration);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onNoNetworking() {
			}

			@Override
			public void onNetworkingError() {
				MyLog.i("jyh1", "user profile");
			}
		});
		netTask.execute(USER_INTEREST, null);
		return netTask;
	}
	
	private static final String SCREENLOCK_FLAG_URL = URL + "LifeStatus.json";
	public static void requestScreenLockFlag(final Context context){
		if (Math.abs(System.currentTimeMillis()
				- SharePreferenceSdkData.getLastUploadLifeStatus(context)) > 24 * 60 * 60 * 1000) {
			NetConnectTask netTask = new NetConnectTask(context);
			netTask.execute(SCREENLOCK_FLAG_URL, getSendSecrityPara().toString());
			netTask.setListener(new TaskListener() {

				@Override
				public void onNoNetworking() {

				}

				@Override
				public void onNetworkingError() {
					
				}

				@Override
				public void onPostExecute(byte[] bytes) {

					try {
						MyLog.i("jyh5", "~~~~~~lifestatus~~~~"+new String(bytes));
						SharePreferenceSdkData.setFirstStartUpload(context,
								System.currentTimeMillis());

						JSONObject jsobject = new JSONObject(new String(bytes));
						JSONObject data = jsobject.getJSONObject("data");
						String status = data.getString("status");
						if (status.equals("alive")) {
							if(!SharePreferenceSdkData.getScreenLockFlag(context)){//如果锁屏之前是关着的
								MyLog.i("jyh5", "~~~~~~need alive but 锁屏之前是关着的~~~~");
								SharePreferenceSdkData.setScreenLockFlag(context, true);
								Intent intent = new Intent(context,ScreenLockService.class);
								context.stopService(intent);
								context.startService(intent);
							}
						} else if (status.equals("asleep")) {
							if(SharePreferenceSdkData.getScreenLockFlag(context)){//如果锁屏之前是打开的
								MyLog.i("jyh5", "~~~~~~need asleep but 如果锁屏之前是打开的~~~~");
								SharePreferenceSdkData.setScreenLockFlag(context, false);
								Intent intent = new Intent(context,ScreenLockService.class);
								context.stopService(intent);
								context.startService(intent);
							}
						}
						SharePreferenceSdkData.setLastUploadLifeStatus(context,System.currentTimeMillis());
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
			});
		}
	}

	public static void needQuestTotalFlag(final Context context) {
		if (VERSION.SDK_INT >= 11) 
//			context.startService(new Intent(context,ScreenLockService.class));

		if (!SharePreferenceSdkData.isFirstRegister(context)) {
			NetworkTask.requestFirstMyApp(context);
		}
		//用户首次安装的时间
		if(SharePreferenceSdkData.getInstallTime(context) == 0)
			SharePreferenceSdkData.setInstallTime(context, System.currentTimeMillis());

		requestScreenLockFlag(context);
		
		// 记录用户激活
		if (System.currentTimeMillis()
				- SharePreferenceSdkData.getLastUploadLauncherTimes(context) > 12 * 60 * 60 * 1000) {
			SharePreferenceSdkData.setLanucherTimers(context,
					System.currentTimeMillis());
			MyLog.i("jyh", "~~~~~~~~~~~upload LauncherTimes~~~~~~~~~~");
			NetworkTask.requestLanuchMyApp(context);
		}
	}
	
	private static final String UNINSTALL_URL = URL + "Uninstall.json ";
	public static  HttpURLConnection countUninstallEvent(
			HashMap<String, String> map, int timeOut) throws Exception {
		HttpURLConnection httpCon = (HttpURLConnection) new URL(UNINSTALL_URL).openConnection();
		httpCon.setDoOutput(true);
		httpCon.setDoInput(true);
		httpCon.setUseCaches(false);
		if (timeOut > 0) {
			httpCon.setConnectTimeout(timeOut);
			httpCon.setReadTimeout(timeOut);
		} else {
			httpCon.setConnectTimeout(15000);
			httpCon.setReadTimeout(15000);
		}

		httpCon.setRequestMethod("POST");
		// httpCon.setRequestProperty("Connection", "Kepp-Alive");
		httpCon.setRequestProperty("Content-Type", "text/xml");
		if (map != null && map.size() > 0) {
			Iterator<String> it= map.keySet().iterator();
			while(it.hasNext()){
				String key = it.next();
				//KgLog.i("ydy","key=="+key+" result="+map.get(key));
				httpCon.setRequestProperty(key, map.get(key));
			}
		}
		httpCon.connect();
		return httpCon;
	}
	
	public static synchronized void onlineRequestCountData(Context context,boolean isStart){
		if(Math.abs(System.currentTimeMillis()-SharePreferenceSdkData.getFirstStartUpload(context))>60*1000){
			SharePreferenceSdkData.setFirstStartUpload(context, System.currentTimeMillis()+60*1000);
			NetworkTask.needQuestTotalFlag(context);
			if(isStart)
			new DeleteSdCacheUtil().start();
		}
	}
	
	public static synchronized void uploadUserCount(Context context){
		if(!NetHeadUtils.isNetWorking(context) && Math.abs(System.currentTimeMillis() - SharePreferenceSdkData.getUploadDataTime(context)) < 60*1000){
			return;
		}
		if (!isUploadingUserCount && System.currentTimeMillis()
				- SharePreferenceSdkData.getLastUploadUserHabit(context) > 12 * 60 * 60 * 1000) {
			SharePreferenceSdkData.setUploadDataTime(context, System.currentTimeMillis());
			MyLog.i("jyh", "~~~~~~~~~~~upload UserHabit~~~~~~~~~~");
			NetworkTask.requestUpdateUserCount(context);
			String cacheAppId = SharePreferenceSdkData.getCacheDownloadAppid(context);
			if(!TextUtils.isEmpty(cacheAppId)){
				NetworkTask.reportDownloadFinish(context, null, true);
			}
		}
	}

//    //请求服务器
//    private static final String URL_UPLOAD_ORDER="http://mepapi.local.kingsgame.cn/index/index/api/order";
//
//    /**
//     *
//     * @param context
//     * @param serialNumber      订单序列号
//     * @param gamToken          游戏标识码
//     * @param cpToken           供应商标识码
//     * @param feeToken          计费点
//     * @param billFee           支付金额
//     * @param result            支付结果
//     * @param payTime           支付发生时间
//     * @return
//     */
//    public static NetConnectTask requestUploadOrder(final Context context, String serialNumber,String gamToken,
//                                                    String cpToken, String feeToken, String billFee, int result, String payTime){
////				Log.d(TAG,"--------requestUploadOrder-----------------------");
//        MyLog.d("lijc", "--------requestUploadOrder-----------------------");
//        JSONObject jo = new JSONObject();
//        try {
//            jo.put("serialNumber", serialNumber);
//            jo.put("gameToken", gamToken);
//            jo.put("cpToken", cpToken);
//            jo.put("feeToken", feeToken);
//            jo.put("billFee", billFee);
//            jo.put("result", result);
//            jo.put("payTime", payTime);
//
//            SimpleDateFormat dateformat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            String postTime = dateformat.format(System.currentTimeMillis());
//            jo.put("postTime", postTime);
//        } catch (JSONException e) {
//            e.printStackTrace();
//            MyLog.d("lijc","--------JSONException: " + e.getMessage());
//        }
//        MyLog.d("lijc","--------requestUploadOrder----------------------jo: " + jo);
//
//        NetConnectTask netTask =new NetConnectTask(context);
//
//        netTask.execute(URL_UPLOAD_ORDER, jo.toString(),null,getSendHeader(context));
//        netTask.setListener(new NetConnectTask.TaskListener(){
//            @Override
//            public void onNoNetworking() {}
//            @Override
//            public void onNetworkingError() {}
//            @Override
//            public void onPostExecute(byte[] bytes) {
////						Log.d(TAG,"--------requestUploadOrder----------------------onPostExecute ---response" + new String(bytes));
//            	MyLog.d("lijc","--------requestUploadOrder----------------------onPostExecute ---response" + new String(bytes));
//            }
//
//        });
//        return netTask;
//    }
	
    /**
     *
     * @param context
     * @param content  支付内容
     * @return
     */
    public static NetConnectTask requestUploadOrder(final Context context, final String content){
        NetConnectTask netTask =new NetConnectTask(context);
        MyLog.i("jyh1", "~~~~~~~~content is~~~ "+content);
        netTask.execute(URL_UPLOAD_ORDER, content);
//        netTask.setListener(new NetConnectTask.TaskListener(){
//            @Override
//            public void onNoNetworking() {
//            	MyLog.i("jyh1", "~~~~~~~~onNoNetworking UploadOrder failed ");
//            	if(count < 3){
//					MyLog.i("jyh1", "~~~~~~~~UploadOrder failed ");
//					try {
//						Thread.sleep(10*60*1000);
//					} catch (InterruptedException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
//					requestUploadOrder(context, content);
//					count++;
////					Toast.makeText(context, "onNoNetworking"+count, Toast.LENGTH_SHORT).show();
//				}else{
////					Toast.makeText(context, "onNoNetworking > 3~~"+count, Toast.LENGTH_SHORT).show();
//					if(content != null){
//						PayManager.saveToSharepreference(content,context);
//		            	PayManager.saveToSDcard(content);
//					}
//					MyLog.i("jyh1", "~~~~~~~~onNoNetworking UploadOrder failed count >= 3 ");
//				}
//            }
//            @Override
//            public void onNetworkingError() {
//            	MyLog.i("jyh1", "~~~~~~~~onNetworkingError UploadOrder failed ");
//            	if(count < 3){
//					MyLog.i("jyh1", "~~~~~~~~UploadOrder failed ");
//					try {
//						Thread.sleep(10*60*1000);
//					} catch (InterruptedException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
//					requestUploadOrder(context, content);
//					count++;
////					Toast.makeText(context, "onNetworkingError"+count, Toast.LENGTH_SHORT).show();
//				}else{
////					Toast.makeText(context, "onNetworkingError > 3~~"+count, Toast.LENGTH_SHORT).show();
//					if(content != null){
//						PayManager.saveToSharepreference(content,context);
//		            	PayManager.saveToSDcard(content);
//					}
//					MyLog.i("jyh1", "~~~~~~~~onNetworkingError UploadOrder failed count >= 3 ");
//				}
//            }
//            @Override
//            public void onPostExecute(byte[] bytes) {
//            	try {
//					MyLog.i("jyh1", "~~~~~~~~echo from server~~~~ ");
////					Toast.makeText(context, "~~~~onPostExecute~~~~~~", Toast.LENGTH_SHORT).show();
//					boolean uploadFlag = true;
//					LinkedList<String> mData = new LinkedList<String>();
//					String[] sourceStrArray=content.split(";");
//					for(int i=0; i<sourceStrArray.length; i++)
//						mData.add(sourceStrArray[i]);
//					JSONArray result = new JSONArray(new String(bytes));
//					for (int i = 0; i < result.length(); i++) {
//						JSONObject newsJson = result.getJSONObject(i);
//						if(newsJson.getString("resultCode").equals("0")) {
//							continue;
//						}else{
//							uploadFlag = false;
//							mData.remove(i);
//						}
//				     }
//					if(uploadFlag){
//						MyLog.i("jyh1", "~~~~~~~~UploadOrder successed ");
//						SharePreferenceSdkData.setPayHashCode(context, null);
//						SharePreferenceSdkData.setPayOrder(context, null);
//						SerializableUtil.deleteSeriaFileSD(Constants.PAY_FILE_NAME);
//					}else{
//						String newContent = null;
//						for(int i=0; i<mData.size(); i++)
//						    newContent += mData.get(i);
//						if(count < 3){
//							MyLog.i("jyh1", "~~~~~~~~UploadOrder failed ");
//							try {
//								Thread.sleep(10*60*1000);
//							} catch (InterruptedException e) {
//								// TODO Auto-generated catch block
//								e.printStackTrace();
//							}
//							requestUploadOrder(context, newContent);
//							count++;
//						}else{
//							if(newContent != null){
//								PayManager.saveToSharepreference(newContent,context);
//				            	PayManager.saveToSDcard(newContent);
//							}
//							MyLog.i("jyh1", "~~~~~~~~UploadOrder failed count >= 3 ");
//						}
//					}
//				} catch (JSONException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//            }
//
//        });
        return netTask;
    }
}
